import { createStoreBindings } from "mobx-miniprogram-bindings";
import { globalStore } from "../../../store/index";
import { logout } from "../../../services/auth";
import { updateProfile } from "../../../services/profile";
import { toast } from "../../../utils/toast";
import { applyTabBar } from "../../../utils/tabBar";

type ChefStats = {
  topDish: string;
  topCount: number;
  bestRatedDish: string;
  bestRatedScore: string;
  lowestDish: string;
  lowestCount: number;
};

Page({
  data: {
    user: globalStore.userProfile,
    isChef: globalStore.isChef,
    chefStats: {
      topDish: "暂无数据",
      topCount: 0,
      bestRatedDish: "暂无数据",
      bestRatedScore: "--",
      lowestDish: "暂无数据",
      lowestCount: 0,
    } as ChefStats,
  },

  storeBindings: null as WechatMiniprogram.Component.TrivialInstance | null,

  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store: globalStore,
      fields: ["userProfile"],
    });
  },

  onUnload() {
    this.storeBindings?.destroyStoreBindings?.();
  },

  async onShow() {
    await globalStore.initAppData();
    const isChef = globalStore.isChef;
    this.setData({ isChef, user: globalStore.userProfile });
    applyTabBar(isChef ? "chef" : globalStore.isDiner ? "diner" : "guest");
    if (!globalStore.userProfile) {
      wx.redirectTo({ url: "/pages/auth/login/index" });
      return;
    }
    if (isChef) {
      this.refreshChefStats();
    }
  },

  handleGoOrders() {
    if (this.data.isChef) {
      wx.switchTab({ url: "/pages/user/cart/index" });
    } else {
      wx.switchTab({ url: "/pages/user/cart/index" });
    }
  },

  handleGoCart() {
    wx.switchTab({ url: "/pages/user/cart/index" });
  },

  handleLogout() {
    wx.showModal({
      title: "退出登录",
      content: "确定要离开甜蜜厨房吗？",
      success: async (res) => {
        if (!res.confirm) return;
        try {
          await logout();
        } catch (error) {
          console.error("logout failed", error);
        } finally {
          globalStore.logout();
          toast("已退出");
          applyTabBar("guest");
          wx.redirectTo({ url: "/pages/auth/login/index" });
        }
      },
    });
  },

  handleChangeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: async (res) => {
        const filePath = res.tempFilePaths?.[0];
        if (!filePath) return;
        try {
          const result = await updateProfile({ avatarUrl: filePath });
          globalStore.setUserProfile(result.user);
          toast("头像已更新");
        } catch (error) {
          console.error("update avatar failed", error);
          wx.showToast({ title: "更新失败", icon: "none" });
        }
      },
      fail: (err) => {
        if (err?.errMsg?.includes("cancel")) return;
        console.error("choose image failed", err);
        wx.showToast({ title: "无法选择图片", icon: "none" });
      },
    });
  },

  refreshChefStats() {
    if (!this.data.isChef) return;
    const menuList = globalStore.menu || [];
    const statsMap = new Map<
      string,
      { name: string; count: number; ratingTotal: number; ratingCount: number }
    >();

    menuList.forEach((item) => {
      statsMap.set(item._id, {
        name: item.name,
        count: 0,
        ratingTotal: 0,
        ratingCount: 0,
      });
    });

    (globalStore.orders || []).forEach((order) => {
      order.items.forEach((item) => {
        if (!statsMap.has(item.menuId)) {
          statsMap.set(item.menuId, {
            name: item.name,
            count: 0,
            ratingTotal: 0,
            ratingCount: 0,
          });
        }
        const entry = statsMap.get(item.menuId)!;
        entry.count += Math.max(1, Number(item.quantity) || 1);
        if (order.review) {
          entry.ratingTotal += order.review.rating;
          entry.ratingCount += 1;
        }
      });
    });

    const records = Array.from(statsMap.entries());
    if (!records.length) {
      this.setData({
        chefStats: {
          topDish: "暂无数据",
          topCount: 0,
          bestRatedDish: "暂无数据",
          bestRatedScore: "--",
          lowestDish: "暂无数据",
          lowestCount: 0,
        },
      });
      return;
    }

    const topEntry = records.reduce((prev, curr) =>
      curr[1].count > prev[1].count ? curr : prev
    );
    const lowestEntry = records.reduce((prev, curr) =>
      curr[1].count < prev[1].count ? curr : prev
    );
    const ratedEntries = records.filter(([, value]) => value.ratingCount > 0);
    const bestEntry = ratedEntries.length
      ? ratedEntries.reduce((prev, curr) => {
          const prevAvg = prev[1].ratingTotal / prev[1].ratingCount;
          const currAvg = curr[1].ratingTotal / curr[1].ratingCount;
          return currAvg > prevAvg ? curr : prev;
        })
      : null;

    this.setData({
      chefStats: {
        topDish: topEntry[1].count ? topEntry[1].name : "暂无数据",
        topCount: topEntry[1].count,
        bestRatedDish: bestEntry ? bestEntry[1].name : "暂无数据",
        bestRatedScore: bestEntry
          ? (bestEntry[1].ratingTotal / bestEntry[1].ratingCount).toFixed(1)
          : "--",
        lowestDish: lowestEntry[1].name,
        lowestCount: lowestEntry[1].count,
      },
    });
  },
});
